<script setup lang="ts">
import { addAddress, editAddress, getAddrDetail } from '@/services/order'
import type { Distpicker, orderInfo, AddrDetail } from '@/types/order'
import { MobileRules, patientNameRules } from '@/utils/rules'
import { computed, inject, onMounted, ref } from 'vue'
import VDistpicker from 'v-distpicker'
import { showFailToast, showSuccessToast } from 'vant'

const props = defineProps<{
  title: string
  addr: orderInfo
}>()
const emits = defineEmits<{
  (e: 'update:showAddressForm', flag: boolean): void
}>()
// 初始化地址信息
const address = ref<AddrDetail>({
  id: '',
  addressDetail: '',
  receiver: '',
  isDefault: 0,
  mobile: '',
  province: '',
  city: '',
  county: '',
  provinceCode: '',
  cityCode: '',
  countyCode: ''
})
onMounted(async () => {
  // 页面渲染完成后，将信息进行复写
  // address.value = props.addr
  if (props.addr.id) {
    const { data } = await getAddrDetail(props.addr.id)
    address.value = data
    localAddr.value.cityCode = data.cityCode
    localAddr.value.countyCode = data.countyCode
    localAddr.value.provinceCode = data.provinceCode
  }
})

const isDefault = computed({
  get() {
    return address.value.isDefault === 1
  },
  set(val) {
    console.log(val)
    address.value.isDefault = Number(val) ? 1 : 0
  }
})
// 保存收获地址信息
const saveLoading = ref(false)
// 依赖注入，通知UserAddress重新获取地址信息
const getLocation = inject<() => void>('getLocation')
const onSubmit = async () => {
  // 判断数据是否齐全
  if (
    address.value.receiver &&
    address.value.mobile &&
    localAddr.value.cityCode &&
    localAddr.value.countyCode &&
    localAddr.value.provinceCode
  ) {
    // 需要判断是编辑状态还是添加状态
    try {
      saveLoading.value = true
      // console.log(address.value)

      console.log({
        ...address.value,
        ...localAddr.value
      })

      props.addr.id
        ? await editAddress(props.addr.id, {
            ...address.value,
            ...localAddr.value
          })
        : await addAddress({
            ...address.value,
            ...localAddr.value
          })
      // 保存完成之后需要关闭弹出框，然后通知爷组件重新获取最新的地址信息，这里可以使用依赖注入
      showSuccessToast(props.addr.id ? '修改成功' : '添加成功')
      getLocation && getLocation()
      emits('update:showAddressForm', false)
    } catch (error) {
      console.log(error)
    } finally {
      saveLoading.value = false
    }
  } else {
    showFailToast('收货地址信息缺少，请填写完成后再提交')
  }
}
// 三联地址
const localAddr = ref({
  provinceCode: '',
  cityCode: '',
  countyCode: ''
})
const onSelected = (data: Distpicker) => {
  localAddr.value.provinceCode = data.province.code
  localAddr.value.cityCode = data.city.code
  localAddr.value.countyCode = data.area.code
}
</script>

<template>
  <div class="address-form">
    <DP-NavBar
      :title="title"
      :back="
        () => {
          emits('update:showAddressForm', false)
        }
      "
    ></DP-NavBar>
    <div class="form">
      <!-- 可以使用 CellGroup 作为容器 -->
      <van-form @submit="onSubmit">
        <van-cell-group :border="false">
          <van-field
            label="收货人"
            placeholder="名字"
            :border="false"
            v-model="address.receiver"
            autocomplete="off"
            maxlength="6"
            :rules="patientNameRules"
          />
          <van-field
            label="手机号码"
            placeholder="手机号"
            :border="false"
            v-model="address.mobile"
            autocomplete="off"
            maxlength="11"
            :rules="MobileRules"
          />
          <div class="local">
            <p class="label">所在地区</p>
            <v-distpicker
              type="mobile"
              @selected="onSelected"
              :province="address.province"
              :city="address.city"
              :area="address.county"
            ></v-distpicker>
          </div>
          <van-field
            label="详细地址"
            placeholder="小区楼栋/乡村名称"
            :border="false"
            type="textarea"
            v-model="address.addressDetail"
            autocomplete="off"
          />
        </van-cell-group>
        <van-cell title="设为默认收货地址" class="default" :border="false">
          <template #value>
            <van-switch size="18px" v-model="isDefault" />
          </template>
        </van-cell>
        <van-button
          block
          round
          type="primary"
          class="save"
          native-type="submit"
          :loading="saveLoading"
          >保存</van-button
        >
      </van-form>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.address-form {
  margin-top: 46px;
  padding: 8px 15px;
  .form {
    :deep(.van-cell-group) {
      margin: unset;
      background: unset;
    }

    :deep(.van-field) {
      padding: 0;
      margin: 10px 0;
    }
    :deep(.van-field__label) {
      width: 60px;
      line-height: 40px;
    }
    :deep(.van-field__value) {
      height: 100%;
      background: #f0eded;
      padding-left: 10px;
      line-height: 40px;
      border-radius: 10px;
      input[id^='van-field'],
      textarea {
        &::placeholder {
          color: rgb(123, 119, 119);
        }
      }
    }
    .default {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0;
      height: 30px;
      :deep(.van-cell__value) {
        display: flex;
        align-items: center;
        justify-content: flex-end;
      }
    }
    .save {
      margin-top: 20px;
    }
  }
  .local {
    .label {
      margin-bottom: 10px;
    }
    .distpicker-address-wrapper {
      height: 262px;
      overflow-y: auto;
      :deep(.address-header) {
        position: fixed;
        width: 92vw;
      }
      :deep(.address-container) {
        margin-top: 40px;
      }
    }
  }
}
</style>
